/****************************************************************************
 *
 *                Admin Over IM
 *
 ****************************************************************************
 *
 *  <Copyright>
 *    Copyright (C) 2008  Basov Alexander
 *
 *  <Unit> connect_test.cpp
 *   <ImplementationNotes>
 *   <PortabilityIssues>
 *   <AnticipatedChanges>
 *****************************************************************************
 *
 *  $Revision: 111 $ $Author: coopht $
 *  $Date: 2008-03-02 13:56:05 +0000 (Sun, 02 Mar 2008) $
 *****************************************************************************/

#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>

#include "jabber.h"

using namespace std;

void err (string msg)
{
  cerr << endl << msg << " : " << strerror (errno) << endl;
  exit (-1);
}

void* srvThread (void* param)
{
  int server_sockfd = 0;
  int client_sockfd = 0;
  struct sockaddr_in net_srv_addr;
  struct sockaddr client_addr;
  size_t client_len = 0;
  size_t server_len = 0;

  char block [BUFSIZ];
  size_t nread;
  string result;

  // Creating new server socket.

  server_sockfd = socket (AF_INET, SOCK_STREAM, 0);
  net_srv_addr.sin_family = AF_INET;
  net_srv_addr.sin_addr.s_addr = htonl (INADDR_ANY);
  net_srv_addr.sin_port = htons (9701);
  server_len = sizeof (net_srv_addr);
  bind (server_sockfd, (struct sockaddr *)&net_srv_addr, server_len);

  // listen for client connection.
  listen (server_sockfd,2);
  
  client_len = sizeof (client_addr);
  client_sockfd = accept (server_sockfd,
			  (struct sockaddr *)&client_addr, &client_len);
  
  
  while ((nread = read (client_sockfd, block, sizeof (block))) > 0)
  {
    char *tmp = (char *)malloc (nread + 1);      
    strncpy (tmp, block, nread + 1);
    
    result.append (string (tmp));
    
    if (tmp != NULL)
      free (tmp);

    if (result != "1234567890")
      err ("WRONG RESULT");
    else 
      break;
  }

  size_t b_left;
  ssize_t b_written;
  const char *ptr = result.c_str ();
  
  b_left = result.size();

  while (b_left > 0)
  {
    if ((b_written = write (client_sockfd, (void*)ptr, b_left)) <= 0)
    {
      if (errno == EINTR)
	b_written = 0;
      else
	err ("ERROR WHILE SENDING");
    }
    
    b_left -= b_written;
    ptr += b_written;  
  }

  if (shutdown (server_sockfd,SHUT_RDWR) != 0)
    err ("SHUTDOWN");
  close (server_sockfd);

}

int main (void)
{
  // creating server thread
  pthread_t srvPid;
  pthread_create (&srvPid, 0, srvThread, (void*)NULL);

  // creating new instance of jabber protocol class
  // and connecting to the server.
  Jabber *j = new Jabber ();
  j->jconnect ("127.0.0.1", 9701);
  j->jsend ("1234567890");

  if (j->jreceive (10) != "1234567890")
    return -1;

  j->jdisconnect ();
  
  return 0;
}
